package com.centanet.framework.network;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RetryPolicy;
import com.centanet.framework.interfaces.HttpCallback;
import com.centanet.framework.interfaces.IRequestEncode;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import java.util.Collections;
import java.util.Map;

/**
 * api
 *
 * @since v3.1
 * Created by guilin on 16/5/24.
 */
public abstract class AbsApi<T> implements IRequestEncode {

    protected final Class<?> mClass;
    protected final HttpCallback<T> mHttpCallback;

    public AbsApi(Class<?> aClass, HttpCallback<T> httpCallback) {
        mClass = aClass;
        mHttpCallback = httpCallback;
    }

    /**
     * 公共ip
     */
    protected abstract String getIp();

    /**
     * 方法
     */
    protected abstract String getPath();

    /**
     * 请求方式,默认GET
     */
    protected int getMethod() {
        return Request.Method.GET;
    }

    /**
     * 请求头信息
     */
    protected Map<String, String> getHeaders() {
        return Collections.emptyMap();
    }

    /**
     * 设置请求参数
     */
    protected abstract void setParams();

    /**
     * 请求策略
     */
    protected RetryPolicy getRetryPolicy() {
        return new DefaultRetryPolicy();
    }

    /**
     * the content type of the POST or PUT body.
     */
    protected String getBodyContentType() {
        return "application/x-www-form-urlencoded; charset=UTF-8";
    }

    /**
     * 是否使用缓存
     */
    protected boolean getShouldCache() {
        return false;
    }

    /**
     * 编码 默认UTF-8
     */
    protected String getParamsEncoding() {
        return "UTF-8";
    }

    /**
     * 创建Gson
     */
    protected Gson gson() {
        return new GsonBuilder().create();
    }

    /**
     * gson泛型解析
     */
    protected abstract TypeToken<T> typeToken();

    /**
     * 开始请求
     */
    public void startRequest() {
        VolleyRequestQueue.getRequestQueue().add(
                new AbsJsonRequest.Builder<>(mClass, getMethod(), url().toString(), mHttpCallback)
                        .headers(getHeaders())
                        .params(params())
                        .bodyContentType(getBodyContentType())
                        .shouldCache(getShouldCache())
                        .retryPolicy(getRetryPolicy())
                        .gson(gson())
                        .typeToken(typeToken())
                        .build());
    }
}
